<?php

namespace App\Console\Commands;

use App\Common\Constant\Params;
use App\Models\Master;
use App\Models\MasterDetail;
use App\Models\MasterStatistic;
use App\Models\MasterWallet;
use App\Models\OldMaster;
use App\Models\Province;
use App\Services\IAreaService;
use App\Services\IMasterService;
use App\Services\IStorageService;
use DB;
use Illuminate\Console\Command;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Collection;
use Log;

class repairMaster extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:repair-master {offset=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修复师傅';

    private $exceptionHandler;
    private $masterService;
    private $storageService;
    private $areaService;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(ExceptionHandler $exceptionHandler,IMasterService $masterService,IStorageService $storageService,IAreaService $areaService)
    {
        parent::__construct();

        $this->exceptionHandler = $exceptionHandler;
        $this->masterService = $masterService;
        $this->storageService = $storageService;
        $this->areaService = $areaService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $bar = $this->output->createProgressBar(Master::count());
        $offset = $this->argument('offset');

        $areas = getAreas();
        
        Master::orderBy('id')->chunk(100, function ($masters) use (&$bar,&$offset,&$areas){
            foreach ($masters as $model) {
                if ($bar->getProgress() < $offset){
                    $this->line("\tMaster [{$model->id}] skip");
                    $bar->advance();
                    continue;
                }

                if (count($model->service_area_ids) < 3){
                    $this->info("\tMaster [{$model->id}] service_area_ids fewer than 3");
                    continue;
                }

                DB::beginTransaction();
                try{
                    $service_area_ids = [];
                    foreach ($model->service_area_ids as $area_id){
                        $area = @$areas[$area_id];
                        if (!$area){
                            continue;
                        }
                        $service_area_ids[] = $area['p'];
                    }
                    $service_area_ids = array_count_values(array_filter($service_area_ids));
                    arsort($service_area_ids);
                    $master_area_id = key($service_area_ids);

                    $service_area_ids = [];
                    foreach ($model->service_area_ids as $area_id){
                        $area = @$areas[$area_id];
                        if (!$area){
                            continue;
                        }
                        if ($area['p'] != $master_area_id){
                            $_area = Province::where('parentid',$master_area_id)->where('name',$area['n'])->first();
                            if (!$_area){
                                continue;
                            }else{
                                $service_area_ids[] = $_area->id;
                            }
                        }else{
                            $service_area_ids[] = $area_id;
                        }
                    }

                    if ($model->service_area_ids == $service_area_ids){
                        DB::commit();
                        $this->info("\tMaster [{$model->id}] no change");
                        continue;
                    }

                    $this->info("\tMaster [{$model->id}] change from (".implode(',',$model->service_area_ids).") to (".implode(',',$service_area_ids).")");
                    $model->service_area_ids = $service_area_ids;
                    $ret = $model->save();
                    if (!$ret){
                        throw new \Exception('master update fail');
                    }

                    DB::commit();
                    $this->info("\tMaster [{$model->id}] success");
                }catch (\Exception $e){
                    DB::rollBack();
                    $this->error("\tMaster [{$model->id}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    Log::error("\tMaster [{$model->id}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    $this->exceptionHandler->report($e);
                }

                $bar->advance();
            }
        });

        $bar->finish();

    }
}
